<template>
  <!-- 关联下属岗位 -->
  <a-modal :afterClose="onAfterClose" @cancel="handleClose" title="关联下属岗位" :visible="visibleJob" :width="isCompany ? '800px' : '1200px'" destroyOnClose>
    <a-row :gutter="10">
      <!-- 侧边栏 -->
      <a-col :span="6" v-if="!isCompany">
        <!-- 公司组织树搜索 -->
        <tree-organization
          ref="treeOrganization"
          @loader="getJobs"
          :expandByAuto="true"
          :selectedKeys.sync="selectedKeys"
          :selectOptions.sync="selectOptions"
          :showChildWithSearch="true"
          :orgQuery="{
            notContainTags: ['EXTEND']
          }"
        />
      </a-col>
      <!-- 主内容 -->
      <a-col :span="isCompany ? 24 : 18">
        <a-radio-group class="mb20" v-model="jobType" :options="type"></a-radio-group>
        <a-spin :spinning="loadingState.isJob">
        <div v-if="isCompany" class="content-box">
          <div class="content-title">
            {{ leftJobs.length }} 项
          </div>
          <div class="content-body">
            <div class="content-row" v-for="item in leftJobs" :key="item.key">
              <span>{{ item.title }}</span>
            </div>
             <a-empty class="content-empty" v-if="!leftJobs.length"/>
          </div>
        </div>
        <a-transfer
          v-else
          :disabled="pageType === 'look'"
          :data-source="leftJobs"
          :target-keys="rightJobs"
          :render="(item) => item.title"
          @change="handleChange"
        />
        </a-spin>
      </a-col>
    </a-row>
    <template slot="footer" style="text-align: right">
      <a-button :loading="loading" type="primary" class="mr20" @click="handleSubmitPost" v-if="!isCompany">提交</a-button>
      <a-button type="primary" @click="handleClose">关闭</a-button>
    </template>
  </a-modal>
</template>

<script>
import { Empty } from 'ant-design-vue'
import TreeOrganization from '@/components/businessComponents/TreeOrganization' // 树
import { getOrgsTree } from '@/api/subassembly/TreeSelectOrganization' // api
import cloneDeep from 'lodash.clonedeep' // 深拷贝
import { isLeaderList, type } from './model'
import { getRightJobs, postsRelation,getPostManageList2 } from '@/api/system/system'
import { getJobListByOrg } from '@/api/system/menuAndAuth.js'

export default {
  name:'a'+Date.now(),
  components: {
    TreeOrganization,
    AEmpty: Empty,
  },
  props: {
    // 显隐控件
    visibleJob: {
      type: Boolean,
      default() {
        return false
      },
    },
    postInfo: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  computed: {
    // 树节点api
    apiTree() {
      return { getOrgsTree }
    },
    isCompany() {
      return this.$route.query.isCompany
    },
    pageType() {
      return this.$route.query.pageType || 'add'
    }
  },
  data() {
    return {
      loadingState: {
        isJob: false,
      },
      key: '',
      selectedKeys: {},
      selectOptions: {},
      loading: false,
      leftJobs: [],
      rightJobs: [],
      postRightJobs: [],
      type: type,
      jobType: 2,
      formModel: {
        orgId: '',
        name: '',
        code: '',
        isLeader: undefined,
        postRelations: [],
      },
    }
  },
  methods: {
    handleClose() {
      this.$emit('handleCancel')
    },
    getJobs() {
      this.loadingState.isJob = true
      getJobListByOrg({ orgId: this.selectedKeys[0] })
        .then((res) => {
          try {
            let leftJobs = this.leftJobs.concat(
              res.data.map((item) => {
                return {
                  title: item.pname || item.name,
                  key: item.id
                }
              })
            )
            let list = []
            leftJobs.forEach((item) => {
              if (!list?.map((i) => i.key)?.includes(item.id)) {
                list.push(item)
              }
            })
            this.leftJobs = list
          } catch (e) {
            console.error(e)
          } finally {
            this.loadingState.isJob = false
          }
        })
        .catch(() => {
          this.loadingState.isJob = false
        })
    },
    handleChange(targetKeys, direction, moveKeys) {
      // console.log(targetKeys, direction, moveKeys)
      if (this.jobType == '') {
        this.$message.info('请选择关联关系')
        return
      }
      this.rightJobs = cloneDeep(targetKeys)

      console.log(this.rightJobs)
    },
    handleSubmitPost() {
      if (this.rightJobs.length > 0) {
        this.rightJobs.forEach((item) => {
          this.postRightJobs.push({ targetId: item, type: this.jobType, sourceId: this.postInfo.id })
        })
      } else {
        this.postRightJobs.push({ targetId: '', type: this.jobType, sourceId: this.postInfo.id })
      }
      this.loading = true

      postsRelation(this.postRightJobs).then((res) => {
        this.$message.success('关联成功')
        this.loading = false
        this.handleClose()
      })
    },
    onAfterClose() {
        this.leftJobs = []
        this.rightJobs = []
        this.postRightJobs = []
    }
  },
  watch: {
    visibleJob(e) {
      if (e) {
        this.$nextTick(() => {
          this.loadingState.isJob = true
          getRightJobs({ id: this.postInfo.id })
            .then((res) => {
              this.loadingState.isJob = false
              if (res.data.postRelations && res.data.postRelations.length > 0) {
                console.log(this.rightJobs)
                this.leftJobs = this.leftJobs.concat(
                  res.data.postRelations.map((item) => {
                    return {
                      title: item.target.pname || item.target.name,
                      key: item.target.id
                    }
                  })
                )
                this.rightJobs = res.data.postRelations.map((item) => item.target.id)
                this.rightJobs = [...new Set(this.rightJobs)]
                this.jobType = res.data.postRelations[0].type
              }
              return true
            })
            .then((res) => {
              this.$refs.treeOrganization && this.$refs.treeOrganization.getList()
            }).catch((e) => {
              this.loadingState.isJob = false
            })
        })
      } else {
        // this.leftJobs = []
        // this.rightJobs = []
        // this.postRightJobs = []
      }
    },
    postInfo(val, oldVal) {
      if (Object.keys(val).length !== 0) {
        // this.form=val
        let isLeader = undefined
        if (val.isLeader === '否') {
          this.formModel.isLeader = 0
        } else if (val.isLeader === '是') {
          this.formModel.isLeader = 1
        }
        this.formModel.name = val.name
        this.formModel.code = val.code
        this.formModel.id = val.id
        this.formModel.orgId = val.orgId
      }
    },
  },
}
</script>
<style lang="less">
.ant-transfer-list {
  width: 45% !important;
  height: 400px !important;
}
</style>
<style lang="less" scoped>
.content-box {
  border: 1px solid #e8e8e8;
  border-radius: 2px 2px 0 0;
  .content-title {
    padding: 6px 12px;
    border-bottom: 1px solid #e8e8e8;
  }
  .content-body {
    height: 400px;
    overflow: auto;
  }
  .content-empty {
    margin-top: 120px;
  }
  .content-row {
    padding: 6px 12px;
  }
}
</style>
